import 'package:flutter/foundation.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class SupabaseService {
  static final SupabaseService _instance = SupabaseService._internal();
  factory SupabaseService() => _instance;
  SupabaseService._internal();

  bool _isInitialized = false;

  /// 初始化方法（极简安全版）
  static Future<void> init() async {
    try {
      if (_instance._isInitialized) return;

      // ✅ 仅保留核心参数（官方最新推荐方式）
      await Supabase.initialize(
        url: 'https://mqjdjoxscqogjtjzffmo.supabase.co',
        anonKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1xamRqb3hzY3FvZ2p0anpmZm1vIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDU4OTMyNTgsImV4cCI6MjA2MTQ2OTI1OH0.wZ3N2GY7SJelB6nlfIhDFpwT5CsVkgv3hf0XhrHVjFg',
      );

      // ✅ 配置深度链接（正确方式）
      Supabase.instance.client.auth.onAuthStateChange.listen((data) {
        debugPrint('Auth状态变更: ${data.event}');
      });

      _instance._isInitialized = true;
      debugPrint('✅ Supabase初始化成功');
    } catch (e, stack) {
      debugPrint('❌ 初始化失败: $e\n$stack');
      rethrow;
    }
  }

  /// 获取客户端实例
  static SupabaseClient get client {
    if (!_instance._isInitialized) {
      throw StateError('请先调用SupabaseService.init()');
    }
    return Supabase.instance.client;
  }
}